package com.qjq.glasses_shopping.service.impl;

import com.qjq.glasses_shopping.service.FileService;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    // 本地存储路径
    private static final String LOCAL_STORAGE_PATH = "D:\\glasseshopping\\target\\classes\\static\\images";

    @Override
    public String uploadImage(byte[] fileBytes, String fileName) {
        if (fileBytes.length > 0) {
            try {
                String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                String uniqueFileName = UUID.randomUUID().toString() + "." + fileSuffix;
                Path filePath = Paths.get(LOCAL_STORAGE_PATH, uniqueFileName);
                Files.createDirectories(filePath.getParent());
                try (FileOutputStream fos = new FileOutputStream(filePath.toFile())) {
                    fos.write(fileBytes);
                    fos.flush();
                }
                // 构建并返回图片的Web URL
                String baseUrl = "http://localhost:8001/images/"; // 假设你的应用部署在根路径下
                return baseUrl + uniqueFileName;

            } catch (IOException e) {
                throw new RuntimeException("文件上传失败", e);
            }
        } else {
            throw new RuntimeException("上传的文件不能为空");
        }
    }

    @Override
    public void delete(String filePath) {
        // 将filePath转换为File对象
        File file = new File(filePath);
        // 删除文件
        if (file.exists() && file.isFile()) {
            file.delete();
        } else {
            // 处理文件不存在或不是文件的情况
            throw new RuntimeException("要删除的文件不存在或不是文件");
        }
    }
}